#include "AudioSystem.h"

using namespace std;

AudioSystem::AudioSystem()
{
	currentBuffer = 0;
}

void AudioSystem::playBuffer(char* audioBuffer, int length)
{
	if (currentBuffer == NUM_OF_BUFFERS)
		currentBuffer = 0;

	bufferData[currentBuffer] = (char*)malloc(length);
	memcpy(bufferData[currentBuffer], audioBuffer, length);

	headers[currentBuffer].lpData = bufferData[currentBuffer];
	headers[currentBuffer].dwBufferLength = length;
	headers[currentBuffer].dwBytesRecorded =  0;
	headers[currentBuffer].dwUser = 0;
	headers[currentBuffer].dwFlags = 0;
	headers[currentBuffer].dwLoops = 0;

	MMRESULT mr;
	if ((mr = waveOutPrepareHeader(audioDevice,&headers[currentBuffer],sizeof(headers[currentBuffer]))) != MMSYSERR_NOERROR)
	{
		char* txt = (char*)malloc(1024);
		waveOutGetErrorText(mr, txt, 1024);
		cout << txt;
	}
	if ((mr = waveOutWrite(audioDevice,&headers[currentBuffer],sizeof(headers[currentBuffer]))) != MMSYSERR_NOERROR)
	{
		char* txt = (char*)malloc(1024);
		waveOutGetErrorText(mr, txt, 1024);
		cout << txt;
	}
	currentBuffer++;
}

//returns length of the data (non header portion) and takes the header out of audioBuffer
void AudioSystem::extractHeaderInfo(FILE* fp)
{
	if (fp) 
	{ 
		BYTE id[4];
		DWORD size;
		short format_tag, channels, block_align, bits_per_sample; 
		DWORD format_length, sample_rate, avg_bytes_sec;
		BYTE junk[8];

		fread(id, sizeof(BYTE), 4, fp);
		if (!memcmp(id, "RIFF", 4)) 
		{
			fread(&size, sizeof(DWORD), 1, fp);
			fread(&id, sizeof(BYTE), 4, fp);
			if (!memcmp(id,"WAVE", 4)) 
			{
				fread(&id, sizeof(BYTE), 4, fp);
				fread(&format_length, sizeof(DWORD),1,fp); 
				fread(&format_tag, sizeof(short), 1, fp); 
				fread(&channels, sizeof(short),1,fp); 
				fread(&sample_rate, sizeof(DWORD), 1, fp); 
				fread(&avg_bytes_sec, sizeof(DWORD), 1, fp); 
				fread(&block_align, sizeof(short), 1, fp); 
				fread(&bits_per_sample, sizeof(short), 1, fp);
				fread(&junk, 8, 1, fp);
			} 
			else 
				printf("Error: RIFF file but not a wave file\n"); 
		} 
		else 
			printf("Error: not a RIFF file\n");
		format.wFormatTag = format_tag;
		format.nChannels  = channels;
		format.nSamplesPerSec = sample_rate;
		format.wBitsPerSample = bits_per_sample;
		format.nBlockAlign = block_align;
		format.nAvgBytesPerSec = avg_bytes_sec;
		format.cbSize = 0;
		MMRESULT mr;
		if ((mr = waveOutOpen(&audioDevice, WAVE_MAPPER, &format, 0, 0, CALLBACK_NULL)) != MMSYSERR_NOERROR)
		{
			char* txt = (char*)malloc(1024);
			waveOutGetErrorText(mr, txt, 1024);
			cout << txt;
			exit(1);
		}
	} 
}